<?php
/**
 * 订单类
 */
namespace app\v2\controller;

use think\Request,
    app\v2\model\UserInfo,
    app\v2\model\UserBankCard,
    think\Db;
use fuiou\FuiouApi;
use app\v2\model\UserOrder;
use app\v2\model\Order;
use app\v2\model\Fuiou as FI;
use think\cache\driver\Redis;
use think\Config;
use app\common\model\Payment;
use app\v2\model\Apply;
    
class FuIou extends Base{
    public function __construct(){
        parent::__construct();
        date_default_timezone_set('Asia/Shanghai');
    }

    /**
     * [bindBankCard 富友绑定银行卡]
     * @return [type] [description]
     */
    public function bindBankCard()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }

        $uid = $isLogin['uid'];
        $param = $this->param;
        if(empty($param['userNm'])||empty($param['credtNo'])||empty($param['acntNo'])||empty($param['bankCd'])){
            return resultArray(['error' =>'缺少参数']); 
        }
        $user = Db::name('user_info')->where('uid', 3)->find();
        
        $UserInfoModel = new UserInfo;
        // 再次绑卡 验证是否本人银行卡
        $userCard = $UserInfoModel->getIdCard($uid);
        if(!empty($userCard)){
            if($param['credtNo'] != $userCard){    
                return resultArray(["error"=>'请检查身份证号码']);      
            }
        }
        // 限制同一身份证绑定多个账号
        $map['id_card'] = $param['credtNo'];
        $map['uid']     = ['neq', $uid];
        $userInfo = $UserInfoModel->where($map)->field('phone')->find();
        if(!empty($userInfo)){
            $str = $userInfo['phone'];
            $phone = substr($str,0,3).'****'.substr($str,-4);
            return resultArray(['error' =>"该身份证已经被{$phone}绑定"]); 
        }
        $data['uid']              = $uid;//签约来源
        $data['name']             = $param["userNm"];//业务类型
        $data['id_card']          = $param['credtNo']; //证件号
        $data['bank_card_number'] = $param['acntNo']; //银行卡号
        $data['bind_mob']         = $param['mobileNo']; //手机号
        $data['user_nm']          = $param['bankCd']; //户名
        $data['create_time']      = date('Y-m-d H:i:s'); //

        //新增认证时间
        $date['bank_auth_date'] = date('Y-m-d H:i:s', time());
        $UserInfoModel->save($date,['uid' => $uid]);


        $userBankCard = new UserBankCard;
        $re = $userBankCard->modifyBankCardPackage($data);
        if(!$re)
        {
            return resultArray(['error' => $userBankCard->getError()]);
        }
        return resultArray(['data' => (new FuiouApi)->returnSignaTureParam($param)]);

    }
    /**
     * [contractNotify 签约异步回调]
     * @return [type] [description]
     */
    public function contractNotify()
    {
        $param = $this->param;
        unset($param['signature']);
        $result = (new FuiouApi)->notifyContract($this->param);
        $date = date('Y-m-d H:i:s');
        if(!$result)
        {
            file_put_contents(LOGS_DIR_NAME.'./conNotify.txt',"验签失败,时间:$date " .json_encode($param)."\n",FILE_APPEND);
            echo 0;
            return;
        }
        $UserBankCard = new UserBankCard;
        $userInfo = new UserInfo;
        //获取最后绑卡的人
        $where['bank_card_number'] = $this->param['acnt_no'];
        $param['status'] = 1;
        $param['contract_no'] = $this->param['contract_no'];
        $bindInfo = $UserBankCard->getCard($where,'id,uid,name,id_card,bank_card_number');
        $UInfo = Db::name('user_info')->field('phone,name,id_card,insurance')->where(['uid' =>$bindInfo['uid']])->find();
        // 启动事务
        Db::startTrans();
        try{
            //更新绑卡状态
            $UserBankCard->saveParam($param,['id'=>$bindInfo['id']]);
            $user['name'] = $bindInfo['name'];
            $user['id_card'] = $bindInfo['id_card'];
            $user['bank_card_number'] = $bindInfo['bank_card_number'];
            //更新个人银行卡信息
            //$userInfo->allowField(true)->save($user,['uid'=>$bindInfo['uid']]);
            //赠送保险
            $params = [];
            if($UInfo['insurance'] == 1) {
                $project = str_replace(['【', '】'],  ['',''], config('message_prefix'));
                $postUrl = 'http://121.196.206.97/insurance/appsvr/life/donate';

                $postData['mobile']     = $UInfo['phone'];//手机号
                $postData['idNo']       = $UInfo['id_card'] ?: $bindInfo['id_card'];//身份证
                $postData['name']       = $UInfo['name'] ?: $bindInfo['name'];//姓名
                $postData['channel']    = 'FA25'; //渠道
                $postData['remark']     = '勾选赠险/'.$project.'/4000以下/职员/小额信用';//是否贷款
                $postData['customerIp'] = getClientIP();//ip

                $insurance = curlPostForm($postUrl,$postData);
                $insurance = json_decode($insurance, true);
                $user['insurance'] = $insurance['bizData']['code'];
            }
            $res = $userInfo->allowField(true)->save($user,['uid'=>$bindInfo['uid']]);
            // 提交事务
            Db::commit();
            file_put_contents(LOGS_DIR_NAME.'./conNotify.txt',"修改状态成功,时间:$date " .json_encode($param)."\n",FILE_APPEND);
            echo 1;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            file_put_contents(LOGS_DIR_NAME.'./conNotify.txt',"修改状态失败,时间:$date " .json_encode($param).$e->getMessage()."\n",FILE_APPEND);
            echo 0;
        }
        return;
    }
    /**
     * [repay 还款]
     * @return [type] [description]
     */
    public function repay()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $no_order = $this->param['no_order'];
        $phone = $this->param['phone'];
        if(!$no_order)
        {
            return resultArray(['error' => '订单错误']);
        }
        $fi = new FI;
        $re = $fi->repay($no_order,$phone);
        if(!$re)
        {
            return resultArray(['error' => $fi->getError()]);
        }
        return resultArray(['data' => '还款成功']);
        
    }

    /**
     * 打款代付回调
     * @author yhq <934797303@qq.com>
     * @date   2018-03-30
     * @param  Request    $request [description]
     * @return [type]              [description]
     */
    public function paySuccess(Request $request)
    {
        $notifyResp = $request->post();

        ## 付款通知参数示例 ##
        // array(11) {
        //   ["amt"] => string(3) "900"
        //   ["result"] => string(43) "渠道资金到账已复核,交易已发送"
        //   ["bankno"] => string(4) "0104"
        //   ["reason"] => string(27) "交易成功，参加清算"
        //   ["merdt"] => string(8) "20180402"
        //   ["accntno"] => string(19) "6217857600005935445"
        //   ["state"] => string(1) "1"
        //   ["orderno"] => string(13) "2018040233892"
        //   ["accntnm"] => string(9) "杨华强"
        //   ["mac"] => string(32) "22975cb490818c2b390db0b299c32648"
        //   ["fuorderno"] => string(12) "421121657483"
        // }
        // 

        ## 退票通知参数示例 ##
        // array(13) {
        //   ["amt"] => string(3) "900"
        //   ["result"] => string(28) "交易已退票,状态成功"
        //   ["futporderno"] => string(12) "552700531313"
        //   ["tpmerdt"] => string(8) "20180402"
        //   ["bankno"] => string(4) "0104"
        //   ["reason"] => string(79) "持卡人身份信息、手机号或CVN2输入不正确，验证失败[1000005]"
        //   ["accntno"] => string(19) "6217857600005935445"
        //   ["merdt"] => string(8) "20180402"
        //   ["state"] => string(1) "1"
        //   ["accntnm"] => string(6) "杨华"
        //   ["orderno"] => string(13) "2018040237014"
        //   ["mac"] => string(32) "f0e04a63f137692f11a0ffda19f8f276"
        //   ["fuorderno"] => string(12) "421513527340"
        // }

        $paymentModel = new Payment;
        $res = $paymentModel->updatePaymentInfo($notifyResp);

        $notifyType = isset($notifyResp['futporderno']) ? '退票通知' : '付款通知'; //通知类型

        if ($res) {
            $returnCode = '1';
            $info = '成功';
        }else{
            $returnCode = '0';
            $info = $paymentModel->getError();
        }

        $time   = date('Y-m-d :H:i:s');
        $result = "[{$time}] 通知类型:{$notifyType} 处理结果:{$info} 回调详情:".json_encode($notifyResp, JSON_UNESCAPED_UNICODE);
        @file_put_contents(LOGS_DIR_NAME.'paymentNotify.log',  $result."\n\n", FILE_APPEND);

        echo $returnCode; //给富友的应答 不要修改 '1'表示成功 其他表示失败
    }


    /**
     * [BindCardList 银行卡列表]
     */
    public function BindCardList()

    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid = $isLogin['uid'];
        $UbcModel = new UserBankCard();
        $bank = $UbcModel->getDataList(['uid' => $uid,'status' => 1],'bank_card_number,user_nm');

        $bankList = [];
        if($bank)
        {
            foreach ($bank as $v) {
                $bcNumber = substr($v['bank_card_number'],-4,4);
                $nm = (new Apply)->switchBank($v['user_nm']);
                //为了快速开发 先这样写  请后期优化
                $logo = Db::name('bank_info')->where(['bank_code' => $v['user_nm']])->field('logo_url,color,back_url')->find();
                $bankList[] = ['bank_card_number' => $bcNumber, 'logo_url' => $logo['logo_url'],'bank_name' => $nm,'color'=>$logo['color'],'back_url'=>$logo['back_url']];
            }
        }
        /*$UserInfoModel = new UserInfo;
        // 再次绑卡 验证是否本人银行卡
        $UserInfo = $UserInfoModel->where('uid', $uid)->field('id_card,phone,name')->find();
        //未绑定银行则不允许查询
        if(!$UserInfo['id_card'] || !$UserInfo['phone']|| !$UserInfo['name'])
        {
            return resultArray(['error' => '信息不全,请补全信息']);
        }
        //凭借参数
        $data['contractNo'] = '';//协议号
        $data['startdt']    = date('Ymd');//开始日期
        $data['enddt']      = date('Ymd');//结束日期
        $data['mobileNo']   = $UserInfo['phone'];//手机号
        $data['userNm']     = $UserInfo['name'];//户名
        $data['acntNo']     = '';//银行卡号
        $data['credtNo']    = $UserInfo['id_card'];//身份证号
        //查询银行卡
        $redis = new Redis;
        $redis -> select(Config::get('redis_select')); //17号库
        $bindInfo = $redis->get('bindCard:'.$uid);
        if($bindInfo)
        {
            return resultArray(['data' => $bindInfo]);
        }
        $fuiouApi = new FuiouApi;
        //获取富友绑定银行卡列表
        $result =  $fuiouApi->cardList($data);
        $jsonRe = json_decode($result,true);
        if(!$jsonRe)
        {
            return resultArray(['error' => '处理失败']);
        }
        if(isset($jsonRe['respCd']) && $jsonRe['respCd'] != '0000')
        {
            return resultArray(['error' => $jsonRe['respDesc']]);
        }
        $data = [];
        //处理两种数据情况
        if(isset($jsonRe['custmrBusi']))
        {
            foreach ($jsonRe['custmrBusi'] as $v) {
                $data[] = $this->handlerData($v);    
            }
        }else{
            $data[] = $this->handlerData($jsonRe);
        }
        $redis->set('bindCard:'.$uid,$data,180);*/
        return resultArray(['data' => $bankList]);


    }
    /**
     * [handlerData 处理一些没必须要返回的数据]
     * @param  array  &$data [description]
     * @return [type]        [description]
     */
    public function handlerData(array &$data = [])
    {
        $datas['userNm']     = $data['userNm'];
        $datas['mobileNo']   = $data['mobileNo'];
        $datas['credtNo']    = $data['credtNo'];
        $datas['acntNo']     = $data['acntNo'];
        $datas['contractNo'] = $data['contractNo'];
        $datas['contractSt'] = $data['contractSt'];
        $datas['respDesc']   = $data['respDesc'];
        return $datas;
    }
    /**
     * [recharge_page 充值页面]
     * @return [type] [description]
     */
    public function rechargePage()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid = $isLogin['uid'];
        return resultArray(['data' => (new Apply)->getUserBankCard($uid)]);
    }
    /**
     * [recharge 充值]
     * @return [type] [description]
     */
    public function recharge()
    {
        $isLogin =  $this->isLogin();  //是否登录
        if(!$isLogin['status']){
            return resultArray(['error' => $isLogin['info']]); 
        }
        $uid = $isLogin['uid'];

        $param = &$this->param;
        //检查金额的确定性
        if(!$param['money'] || $param['money'] < 5)
        {
            return resultArray(['error' => '金额不得少于五元']);
        }
        //检查银行卡的合法性
        $userBankCard =  new UserBankCard;
        $cardInfo = $userBankCard->checkBank($param['bankId'], $uid)->toArray();
        if(!$cardInfo)
        {
            return resultArray(['error' => $userBankCard->getError()]);
        }
        $fi = new FI;
        //开始支付
        $result = $fi->recharge($param,$cardInfo);
        if(!$result)
        {
            return resultArray(['error' => $fi->getError()]);
        }
        //未签约
        if($result === 'noContract')
        {
            return resultArray(['error' => $fi->getError(),'code' => 401]);
        }
        return resultArray(['data' => '支付成功']);
    }

    /**
     * [handlerTimeOut 处理超时]
     * @return [type] [description]
     */
    public function handlerTimeOut()
    {
        $param =  &$this->param;
        if(!isset($param['order_number']) || empty($param['order_number']))
        {
            return resultArray(['error' => '参数错误']);
        }

        $fi = new FI;
        $result = $fi->handlerTimeOut($param['order_number']);
        if(!$result)
        {
            return resultArray(['error' => $fi->getError()]);
        }
        return resultArray(['data' => $result]);
    }

}
